﻿// Copyright 2006 - Ricardo Stuven (rstuven@gmail.com)
//
// This file is part of MsSqlSpatial.
// MsSqlSpatial is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// MsSqlSpatial is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public License
// along with MsSqlSpatial; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using MsSqlSpatial;

public partial class StoredProcedures
{
	/// <summary>
	/// Remove a geometry column from a spatial table.
	/// </summary>
	[SqlProcedure]
	public static void DropGeometryColumn(
		SqlString schema_name,
		SqlString table_name,
		SqlString column_name)
	{
		//1.  drop the spatial reference Check Constraint on the feature table
		//2.  drop the entry from the GEOMETRY_COLUMNS table
		//3.  drop the geometry column from the feature table

		using (SqlConnection connection = DatabaseHelper.ContextConnection)
		{
			connection.Open();
			SqlTransaction transaction = connection.BeginTransaction();
			try
			{
				using (SqlCommand command = connection.CreateCommand())
				{
					command.Transaction = transaction;
					string schemaName = DatabaseHelper.CheckSchemaName(command, schema_name);
					string tableName = table_name.Value;
					string columnName = column_name.Value;
					
					if (!GeometryColumnsTable.CheckGeometryColumnExists(command, schemaName, tableName, columnName))
					{
						throw new ApplicationException("Column not found in [ST].[GEOMETRY_COLUMNS] table.");
					}

					GeometryTable.ExecuteDropColumnDependantObjects(command, schemaName, tableName, columnName);
					DatabaseHelper.DropColumn(command, schemaName, tableName, columnName);
	
					// If you add more associated objects to the dropped column, please 
					// verify whether they have to be added to "DropGeometryTable" method as well.
					
					transaction.Commit();
					SqlContext.Pipe.Send(string.Format(
@"Column [{0}].[{1}].[{2}] removed."
, schemaName, tableName, columnName));
				}
			}
			catch
			{
				transaction.Rollback();
				throw;
			}
		}
	}

};
